package com.demo.sender.notice.telegram;

import com.alibaba.fastjson2.JSON;
import com.demo.common.ResultData;
import com.demo.request.NoticeBaseReq;
import com.demo.sender.notice.NoticeSenderService;
import com.demo.sender.notice.telegram.enums.TelegramTypeEnum;
import com.demo.sender.notice.telegram.request.TelegramMessageReq;
import com.demo.sender.notice.telegram.response.TelegramResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 文档地址：<a href="https://core.telegram.org/bots/api">https://core.telegram.org/bots/api</a>
 *
 * @author wangfengchen
 */
@Slf4j
@Component
public class TelegramSender implements NoticeSenderService {


  @Autowired
  private RestTemplate restTemplate;


  @Override
  public ResultData<Object> send(NoticeBaseReq req) {
    TelegramTypeEnum typeEnum = TelegramTypeEnum.match(req.getMsgType());
    if (ObjectUtils.isEmpty(typeEnum)) {
      return ResultData.fail("消息类型错误");
    }
    TelegramMessageReq telegramMessageReq = new TelegramMessageReq();
    telegramMessageReq.setChat_id(req.getChatId());
    telegramMessageReq.setParse_mode(req.getMsgType());
    telegramMessageReq.setText(req.getContent());
    return send(req.getWebhook(), telegramMessageReq);
  }

  /**
   * 消息发送
   *
   * @param webhook
   * @param req
   * @return
   */
  private ResultData<Object> send(String webhook, TelegramMessageReq req) {
    String botUrl = "https://api.telegram.org/bot%s/sendMessage";
    String url = String.format(botUrl, webhook);
    log.info("telegram消息发送，url = {}，request = {}", url, JSON.toJSONString(req));
    ResponseEntity<TelegramResult> respEntity = this.restTemplate.postForEntity(url, req, TelegramResult.class);
    log.info("telegram消息发送，respEntity = {}", JSON.toJSONString(respEntity));
    if (ObjectUtils.isEmpty(respEntity)) {
      log.warn("telegram消息发送失败");
      return ResultData.fail(501, "telegram消息发送异常,直接返回");
    }
    if (respEntity.getStatusCode().value() != HttpStatus.OK.value() || respEntity.getBody() == null) {
      return ResultData.fail(respEntity.getStatusCodeValue(), respEntity.toString());
    }
    TelegramResult result = respEntity.getBody();
    log.info("result = {} ", result);
    int code = result.getCode();
    if (code != 0) {
      log.error("telegram消息发送失败, result = {} ", result);
      return ResultData.fail(code);
    } else {
      return ResultData.success();
    }
  }


}
